//
//  VerifiedViewController.m
//  CBT
//
//  Created by Mr.Zhang on 2018/11/21.
//  Copyright © 2018 Mr.Zhang. All rights reserved.
//

#import "VerifiedViewController.h"
#import "LYLPhotoTailoringTool.h"

#import "UserManager.h"

#import "Bolts.h"

@interface VerifiedViewController ()

@property (nonatomic, strong) NSMutableArray *positiveImageArray;
@property (nonatomic, strong) NSMutableArray *negativeImageArray;

@property (nonatomic, strong) UIButton *submitBtn;

@end

@implementation VerifiedViewController

#pragma mark - VC Life

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = kLocalizedString(@"实名认证", nil);
    
    [self initSubViews];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [UIApplication sharedApplication].statusBarHidden = NO;
}

- (void)initSubViews
{
    @weak(self)
    UIButton *positiveBtn = [[UIButton alloc]initWithFrame:CGRectMake(25, 30, 228, 141)];
    [positiveBtn setBackgroundImage:[UIImage imageNamed:@"sfz_zheng"] forState:(UIControlStateNormal)];
    [positiveBtn setImage:[UIImage imageNamed:@"IDCard"] forState:(UIControlStateNormal)];
    positiveBtn.centerX = self.view.centerX;
    [positiveBtn bk_whenTapped:^{
        [[LYLPhotoTailoringTool sharedTool]photoTailoringIsRoundImage:NO finish:^(UIImage *image) {
            image = [UIImage fixOrientation:image];
            self_weak_.positiveImageArray = [NSMutableArray array];
            [self_weak_.positiveImageArray addObject:image];
            [positiveBtn setImage:image forState:(UIControlStateNormal)];
            
            if (self_weak_.negativeImageArray.count > 0) {
                self_weak_.submitBtn.userInteractionEnabled = YES;
                self_weak_.submitBtn.backgroundColor = DefaultBlueColor;
            }
        }];
    }];
    [self.view addSubview:positiveBtn];
    
    UILabel *positiveLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, positiveBtn.bottom  + 12, ScreenNarrowSide, [NSString sizeWithString:kLocalizedString(@"身份证，护照等有效证件正面照", nil) font:[UIFont systemFontOfSize:15] width:ScreenNarrowSide height:0])];
    positiveLabel.text = kLocalizedString(@"身份证，护照等有效证件正面照", nil);
    positiveLabel.textColor = UIColorFromRGB(0x333333);
    positiveLabel.textAlignment = NSTextAlignmentCenter;
    positiveLabel.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:positiveLabel];
    
    UIButton *negativeBtn = [[UIButton alloc]initWithFrame:CGRectMake(25, positiveLabel.bottom + 26, 228, 141)];
    [negativeBtn setBackgroundImage:[UIImage imageNamed:@"sfz_fan"] forState:(UIControlStateNormal)];
    [negativeBtn setImage:[UIImage imageNamed:@"IDCard"] forState:(UIControlStateNormal)];
    negativeBtn.centerX = self.view.centerX;
    
    [negativeBtn bk_whenTapped:^{
        [[LYLPhotoTailoringTool sharedTool]photoTailoringIsRoundImage:NO finish:^(UIImage *image) {
            image = [UIImage fixOrientation:image];
            self_weak_.negativeImageArray = [NSMutableArray array];
            [self_weak_.negativeImageArray addObject:image];
            [negativeBtn setImage:image forState:(UIControlStateNormal)];
            
            if (self_weak_.positiveImageArray.count > 0) {
                self_weak_.submitBtn.userInteractionEnabled = YES;
                self_weak_.submitBtn.backgroundColor = DefaultBlueColor;
            }
        }];
    }];
    [self.view addSubview:negativeBtn];
    
    UILabel *negativeLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, negativeBtn.bottom  + 12, ScreenNarrowSide, [NSString sizeWithString:kLocalizedString(@"身份证，护照等有效证件背面照", nil) font:[UIFont systemFontOfSize:15] width:ScreenNarrowSide height:0])];
    negativeLabel.text = kLocalizedString(@"身份证，护照等有效证件背面照", nil);
    negativeLabel.textColor = UIColorFromRGB(0x333333);
    negativeLabel.textAlignment = NSTextAlignmentCenter;
    negativeLabel.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:negativeLabel];
    
    _submitBtn = [[UIButton alloc]initWithFrame:CGRectMake(25, negativeLabel.bottom + 50, ScreenNarrowSide - 50, 40)];
    [_submitBtn setTitle:kLocalizedString(@"确定", nil) forState:(UIControlStateNormal)];
    
    _submitBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    _submitBtn.backgroundColor = UIColorFromRGB(0xDBDBDB);
    _submitBtn.layer.cornerRadius     = 20;
    _submitBtn.layer.masksToBounds    = YES;
    _submitBtn.userInteractionEnabled = NO;
   
    [_submitBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    
    [_submitBtn addTarget:self action:@selector(submitBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];

    [self.view addSubview:_submitBtn];
}

-(void)submitBtnAction:(UIButton *)btn
{
    if ([NSArray isArrayEmpty:self.positiveImageArray]) {
        [HFStatusView showFailureMessage:kLocalizedString(@"请上传身份证，护照等正面照",nil)];
        return;
    }
    
    if ([NSArray isArrayEmpty:self.negativeImageArray]) {
        [HFStatusView showFailureMessage:kLocalizedString(@"请上传身份证，护照等背面照",nil)];
        return;
    }
    
    [self startClearBgColorLoading];

    [self allRequest];
}

#pragma mark - NetWork

//正面照
- (BFTask *)positiveRequestNetWork
{
    BFTaskCompletionSource *source = [BFTaskCompletionSource taskCompletionSource];
    
    [UserManager setUserIDcardWithUserId:[CBTLocalUserManager sharedInstance].userId type:@"1" image:self.positiveImageArray[0] block:^(id data, HttpRequestResult result, NSString *msg) {
        if (result == kHttpRequestResultNormal) {
            [source setResult:@{@"key": @"success",@"name":@"positiveRequest"}];
        }else{
            [source setError:[NSError errorWithDomain:@"ErrorDomain" code:-1 userInfo:@{@"name":@"positiveRequest"}]];
        }
    }];
    return source.task;
}

//背面照
- (BFTask *)negativeRequestNetWork
{
    BFTaskCompletionSource *source = [BFTaskCompletionSource taskCompletionSource];
    
    [UserManager setUserIDcardWithUserId:[CBTLocalUserManager sharedInstance].userId type:@"2" image:self.negativeImageArray[0] block:^(id data, HttpRequestResult result, NSString *msg) {
        if (result == kHttpRequestResultNormal) {
            [source setResult:@{@"key": @"success",@"name":@"negativeRequest"}];
        }else{
            [source setError:[NSError errorWithDomain:@"ErrorDomain" code:-1 userInfo:@{@"name":@"negativeRequest"}]];
        }
    }];
    return source.task;
}


-(void)allRequest
{
    @weak(self)
    
    [[BFTask taskForCompletionOfAllTasks:@[[self positiveRequestNetWork], [self negativeRequestNetWork]]] continueWithBlock:^id _Nullable(BFTask * _Nonnull t) {
        
        NSArray *errorArray = t.error.userInfo[@"errors"];
        
        BOOL negativeRequestFinish = NO;
        BOOL positiveRequestFinish = NO;
        
        if (errorArray.count > 0) {
            for (NSError *dic in errorArray) {
                if ([dic.userInfo[@"name"] isEqualToString:@"negativeRequest"]){
                    negativeRequestFinish = YES;
                }
                
                if ([dic.userInfo[@"name"] isEqualToString:@"positiveRequest"]) {
                    positiveRequestFinish = YES;
                }
            }
        }else if (t.error.userInfo.count > 0){
            if ([t.error.userInfo[@"name"] isEqualToString:@"negativeRequest"]){
                 negativeRequestFinish = YES;
            }
            if ([t.error.userInfo[@"name"] isEqualToString:@"positiveRequest"]) {
                 positiveRequestFinish = YES;
            }
        }
        
        if (negativeRequestFinish == NO && positiveRequestFinish == NO) {
            [self_weak_ stopLoading];
            [[CBTLocalUserManager sharedInstance]refreshUserInfoDic:@{@"flag":@"2"}];
            if (self_weak_.finishBlock != nil) {
                self_weak_.finishBlock();
            }
            [self_weak_.navigationController popViewControllerAnimated:YES];
            [HFStatusView showSuccessMessage:kLocalizedString(@"上传成功", nil)];
        }else if (negativeRequestFinish == YES && positiveRequestFinish == NO) {
            [self_weak_ stopLoading];
            [HFStatusView showFailureMessage:kLocalizedString(@"身份证或护照正面照上传失败",nil)];
        }else if (negativeRequestFinish == NO && positiveRequestFinish == YES) {
            [self_weak_ stopLoading];
            [HFStatusView showFailureMessage:kLocalizedString(@"身份证或护照背面照上传失败",nil)];
        }
        
        return nil;
    }];
}

#pragma mark - Lazy

- (NSMutableArray *)positiveImageArray
{
    if (!_positiveImageArray) {
        _positiveImageArray = [NSMutableArray array];
    }
    return _positiveImageArray;
}

- (NSMutableArray *)negativeImageArray
{
    if (!_negativeImageArray) {
        _negativeImageArray = [NSMutableArray array];
    }
    return _negativeImageArray;
}


@end
